//
//  EcgNetReq.m
//  CareRingApp
//
//  Created by Linktop on 2024/9/10.
//

#import "EcgNetReq.h"


@implementation EcgNetReq

+(void)ecgNetRowWaveFilter:(NSString *)host
          DataArray:(NSArray<NSNumber *> *)rowVolArray
                       Key:(NSString *)key
                        Sn:(NSString *)sn
                       MacAddr:(NSString *)mac
                      Sign:(NSString *)sign
            AndComplated:(void (^)(NSHTTPURLResponse * _Nullable httpResp,  NSDictionary * _Nullable content, NSArray<NSNumber *> * _Nullable processedValues)) handler
            AndServerNil:(void (^)(void))servernil
{

    NSString *urlSuff =  @"o2m/ecg/spe";


    
    // key
    NSString * keyEncode = [NetTools URLEncodeString:key];
    NSString * macEncode = [NetTools URLEncodeString:mac];
    
    NSString *arguments = [NSString stringWithFormat:@"_key=%@&sn=%@&mac=%@&_sign=%@", keyEncode, sn,macEncode, sign];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@/%@?%@", host, urlSuff, arguments]];
    DebugNSLog(@"%s url : %@", __FUNCTION__ , url);
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];

    NSMutableString *bodyString = [NSMutableString new];
    for (NSNumber *num in rowVolArray) {
        NSString *tmp = [NSString stringWithFormat:@"%d,1\n", (int)(num.floatValue * 1000)];
        [bodyString appendString:tmp];
        
    }

    
    NSMutableData* bodyData = [NSMutableData data];
    [bodyData appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    
    //第三步，连接服务器
    
    [request setHTTPBody:bodyData];
    
    //第二步，创建请求
    __weak typeof(self) weakSelf = self;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;

        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
        NSInteger statecode = httpResp.statusCode;
        //            DebugNSLog(@"上传结束: %@ 结果:%ld", tableName, statecode);
        if (statecode == 301) { // app自行跳转新地址
            
            DebugNSLog(@"ecg/spe 301");
            if (data)
            {// 解析新域名
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            }
        }
        if (statecode != 200) {
            // statecode = 403 表示无账号权限,即token和上报账号不匹配
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(httpResp, nil, nil);
            });
            return;
        }
        
        NSDictionary* dic = nil;
        NSArray<NSNumber *> *processedValues = nil;
        if (data)
        {
            
            dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            /*
             state 0:无错误
             */
            //                DebugNSLog(@"上传数据 应答:%@", dic);
            NSDictionary *processedSignal = dic[@"processedSignal"];
            NSDictionary *processedDataSamples =  processedSignal[@"processedDataSamples"];
            processedValues = processedDataSamples[@"processedValues"];// 滤波后的波形数据
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(httpResp, dic, processedValues);
        });
    }];
    [sessionTask resume];
        
        
//    }];

}



/// 计算ecg结论
/// - Parameters:
///   - host:
///   - rowVolArray:
///   - t:
///   - handler:
///   - servernil:
+(void)ecgNetArrhythmia:(NSString *)host
          DataArray:(NSArray<NSNumber *> *)rowVolArray
                    Key:(NSString *)key
                     Sn:(NSString *)sn
                    MacAddr:(NSString *)mac
                   Sign:(NSString *)sign
            AndComplated:(void (^)(NSHTTPURLResponse * _Nullable httpResp,  NSDictionary * _Nullable content, NSArray<NSNumber *> * _Nullable processedValues)) handler
            AndServerNil:(void (^)(void))servernil
{

    NSString *urlSuff =  @"o2m/ecg/arrhythmia";

    // t
    NSString * keyEncode = [NetTools URLEncodeString:key];
    NSString * macEncode = [NetTools URLEncodeString:mac];
    
    NSString *arguments = [NSString stringWithFormat:@"_key=%@&sn=%@&mac=%@&_sign=%@", keyEncode, sn,macEncode, sign];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@/%@?%@", host, urlSuff, arguments]];
    DebugNSLog(@"%s url : %@", __FUNCTION__ , url);
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];

    NSMutableString *bodyString = [NSMutableString new];
    for (NSNumber *num in rowVolArray) {
        NSString *tmp = [NSString stringWithFormat:@"%d,1\n", (int)(num.floatValue * 1000)];
        [bodyString appendString:tmp];
        
    }

    
    NSMutableData* bodyData = [NSMutableData data];
    [bodyData appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    
    //第三步，连接服务器
    
    [request setHTTPBody:bodyData];
    
    //第二步，创建请求
    __weak typeof(self) weakSelf = self;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
        NSInteger statecode = httpResp.statusCode;
        //            DebugNSLog(@"上传结束: %@ 结果:%ld", tableName, statecode);
        if (statecode == 301) { // app自行跳转新地址
            
            DebugNSLog(@"ecg/spe 301");
            if (data)
            {// 解析新域名
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            }
        }
        if (statecode != 200) {
            // statecode = 403 表示无账号权限,即token和上报账号不匹配
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(httpResp, nil, nil);
            });
            return;
        }
        
        NSDictionary* dic = nil;
        NSArray<NSNumber *> *processedValues = nil;
        if (data)
        {
            
            dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            /*
             state 0:无错误
             */
//            //                DebugNSLog(@"上传数据 应答:%@", dic);
//            NSDictionary *processedSignal = dic[@"processedSignal"];
//            NSDictionary *processedDataSamples =  processedSignal[@"processedDataSamples"];
//            processedValues = processedDataSamples[@"processedValues"];// 滤波后的波形数据
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(httpResp, dic, processedValues);
        });
    }];
    [sessionTask resume];
        
        
//    }];

}


@end
